var api = require("../../config/api");
var keys = require('../../config/keys.js');
var amap = require('../../libs/amap-wx.130.js');

// pages/FirstPage/FirstPage.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        region: '',
        currentDate: '',
        FirstPageContent: [],
        electricianCode: '',
        isNext: false,
        mPageNum: 1,
        unreadNum: 0,
        footer: {},
        cusTitle: '午羊智慧电力在线检测运维系统',
        statusBarHeight: 0,
        toBarHeight: 44,

        viewIndex: 1
    },

    /**
     * 点击待派遣
     */
    switchLeft: function () {
        this.setData({
            viewIndex: 1,
        });
        this.fetchFirstpageContent_accept();
        // this.doHttpGetHikFeedbackStatistics()
        // this.doHttpGetHikFeedbackStatisticsList()
    },

    /**
     * 点击待抢单
     */
    switchRight: function () {
        this.setData({
            viewIndex: 2,
        });
        this.fetchFirstpageContent_grab();
        // this.doHttpGetHikFeedbackStatistics()
        // this.doHttpGetHikFeedbackStatisticsList()
    },

    /** 
     * 获取派遣订单信息
     */
    fetchFirstpageContent_accept() {
        var that = this;
        // 直接向后台获取可以进行接单或抢单的订单
        // 获取到本地用户信息，就可以请求网络
        wx.request({
            url: api.findAllToIndex,
            method: 'POST',
            data: {
                // 向后台请求数据，查看当前可以接单或抢单的订单号
                electricianCode: that.data.electricianCode,
                feedbackRegion: "",
                // feedbackRegion: that.data.region,
                workOrderType: 1,
                pageNum: that.data.mPageNum,
                pageSize: '5',
            },
            // 向后台请求数据成功，获得了当前可以进行接单或抢单的订单
            success: (res) => {
                if (res.data.code == 200) {
                    // 筛选 workOrderType == 1 的订单
                    const filteredOrders = res.data.data.rows.filter(order => order.workOrderType == 1);
                    if (that.data.mPageNum != 1) {
                        that.setData({
                            FirstPageContent: that.data.FirstPageContent.concat(filteredOrders)
                            // FirstPageContent: that.data.FirstPageContent.concat(res.data.data.rows)
                        });
                    } else {
                        that.setData({
                            FirstPageContent: filteredOrders
                            // FirstPageContent: res.data.data.rows
                        });
                    }
                    // 查看请求到的数据，在控制台打印
                    console.log('查询到接单的订单信息', res.data.data)
                    // 将数组数据保存
                    // const FirstPageData = res.data.data.rows;
                    /*this.setData({
                        // 把后台的数组内容传递给前端，方便页面的渲染
                        FirstPageContent: FirstPageData,
                    });*/
                } else {
                    wx.showToast({
                        title: res.data.mesage,
                        icon: 'none'
                    })
                }
                this.setData({
                    isNext: true,
                });
            },
            fail() {
                wx.showToast({
                    title: '请求可接受订单信息失败',
                    icon: 'none'
                })
            },
        })
    },

    /** 
     * 获取抢单信息
     */
    fetchFirstpageContent_grab() {
        var that = this;
        // 直接向后台获取可以进行接单或抢单的订单
        // 获取到本地用户信息，就可以请求网络
        wx.request({
            url: api.findAllToIndex,
            method: 'POST',
            data: {
                // 向后台请求数据，查看当前可以接单或抢单的订单号
                electricianCode: that.data.electricianCode,
                feedbackRegion: "",
                // feedbackRegion: that.data.region,
                workOrderType: 2,
                pageNum: that.data.mPageNum,
                pageSize: '5',
            },
            // 向后台请求数据成功，获得了当前可以进行接单或抢单的订单
            success: (res) => {
                if (res.data.code == 200) {
                    // 筛选 workOrderType == 1 的订单
                    const filteredOrders = res.data.data.rows.filter(order => order.workOrderType == 2);
                    if (that.data.mPageNum != 1) {
                        that.setData({
                            FirstPageContent: that.data.FirstPageContent.concat(filteredOrders)
                            // FirstPageContent: that.data.FirstPageContent.concat(res.data.data.rows)
                        });
                    } else {
                        that.setData({
                            FirstPageContent: filteredOrders
                            // FirstPageContent: res.data.data.rows
                        });
                    }
                    // 查看请求到的数据，在控制台打印
                    console.log('查询到抢单的订单信息', res.data.data)
                    // 将数组数据保存
                    // const FirstPageData = res.data.data.rows;
                    /*this.setData({
                        // 把后台的数组内容传递给前端，方便页面的渲染
                        FirstPageContent: FirstPageData,
                    });*/
                } else {
                    wx.showToast({
                        title: res.data.mesage,
                        icon: 'none'
                    })
                }
                this.setData({
                    isNext: true,
                });
            },
            fail() {
                wx.showToast({
                    title: '请求可接受订单信息失败',
                    icon: 'none'
                })
            },
        })
    },

    /**
     * 初始化底部Tab数据
     */
    getfooter: function () {
        var that = this
        wx.getStorage({
            key: 'electricianCode',
            success: (RES) => {
                this.setData({
                    electricianCode: RES.data.electricianCode,
                });
                console.log('electricianCode为', RES.data.electricianCode)
                wx.request({
                    url: api.findUnread,
                    method: 'POST',
                    data: {
                        electricianCode: that.data.electricianCode,
                    },
                    success: function (res) {
                        if (res.data.code == 200) {
                            that.setData({
                                    unreadNum: res.data.data.unreadNum,
                                }),
                                console.log("未读消息数量:", that.data.unreadNum)
                            var footerList = {
                                footerTab: 0,
                                footerlist: [{
                                    diy_name: "系统首页",
                                    color: '#221915',
                                    img: "",
                                    selimg: "",
                                    link: "/pages/FirstPage/FirstPage",
                                    unreadNum: that.data.unreadNum,
                                }, {
                                    diy_name: "我的工单",
                                    color: '#221915',
                                    img: "",
                                    selimg: "",
                                    link: "/pages/MyList/MyList"
                                }, {
                                    diy_name: "个人中心",
                                    color: '#221915',
                                    img: "",
                                    selimg: "",
                                    link: "/pages/Mine/Mine"
                                }]
                            }
                            that.setData({
                                footer: footerList
                            })
                        }

                    }
                })
            },
        });



    },

    // 获取定位
    getMapInfo: function () {
        var that = this;
        var myAmapFun = new amap.AMapWX({
            key: keys.amapKey
        });
        myAmapFun.getRegeo({
            success: function (data) {
                console.log('返回的地理位置信息', data[0])
                const LocationInfo = data[0].regeocodeData.addressComponent;
                console.log('LocationInfo的内容', LocationInfo)
                that.setData({
                    region: LocationInfo.district,
                })
            },
            fail: function (info) {}
        })
    },
    // 更新日期
    updateDate: function () {
        const date = new Date();
        const year = date.getFullYear(); // 获取年份
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份（+1是因为月份从0开始）
        const day = String(date.getDate()).padStart(2, '0'); // 获取日期，确保两位数

        const formattedDate = `${year}-${month}-${day}`; // 格式化为 "YYYY-MM-DD" 格式

        this.setData({
            currentDate: formattedDate
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let sysinfo = wx.getSystemInfoSync();
        this.setData({
            statusBarHeight: sysinfo.statusBarHeight
        })

        this.getfooter();
        this.getMapInfo();
        // 先从本地获取到电工的信息
        wx.getStorage({
            key: 'electricianCode',
            success: (RES) => {
                this.setData({
                    electricianCode: RES.data.electricianCode
                })
                if (this.data.viewIndex == 1) {
                    this.fetchFirstpageContent_accept();
                }
                if (this.data.viewIndex == 2) {
                    this.fetchFirstpageContent_grab();
                }
            },
        })
        // 页面刷新日期
        this.updateDate();
    },


    // fetchFirstpageContent(){
    //     var that = this;
    //     // 直接向后台获取可以进行接单或抢单的订单
    //     // 获取到本地用户信息，就可以请求网络
    //     wx.request({
    //       url: api.findAllToIndex,
    //       method: 'POST',
    //       data: {
    //         // 向后台请求数据，查看当前可以接单或抢单的订单号
    //         electricianCode: this.data.electricianCode,
    //         pageNum: that.data.mPageNum,
    //         pageSize: '5',
    //       },
    //       // 向后台请求数据成功，获得了当前可以进行接单或抢单的订单
    //       success: (res) => {
    //         if(res.data.code == 200){
    //             if(that.data.mPageNum != 1){
    //                 that.setData({
    //                     FirstPageContent: that.data.FirstPageContent.concat(res.data.data.rows)
    //                 });
    //             }else{
    //                 that.setData({
    //                     FirstPageContent: res.data.data.rows
    //                 });
    //             }
    //               // 查看请求到的数据，在控制台打印
    //               console.log('查询到的订单信息', res.data.data)
    //               // 将数组数据保存
    //               // const FirstPageData = res.data.data.rows;
    //               /*this.setData({
    //                   // 把后台的数组内容传递给前端，方便页面的渲染
    //                   FirstPageContent: FirstPageData,
    //               });*/
    //         }else{
    //             wx.showToast({
    //               title: res.data.mesage,
    //               icon: 'none'
    //             })
    //         }
    //         this.setData({
    //             isNext: true,
    //         });
    //       },
    //       fail(){
    //         wx.showToast({
    //           title: '请求可接受订单信息失败',
    //           icon: 'none'
    //         })
    //       },
    //     })
    // },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getfooter();
        wx.hideHomeButton();
        this.getMapInfo();
        if (this.data.isNext == true) {
            if (this.data.viewIndex == 1) {
                this.fetchFirstpageContent_accept();
            }
            if (this.data.viewIndex == 2) {
                this.fetchFirstpageContent_grab();
            }

            // 页面刷新日期
            this.updateDate();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        var that = this;
        that.setData({
            mPageNum: 1
        });
        // 刷新页面订单数据
        if (this.data.viewIndex == 1) {
            this.fetchFirstpageContent_accept();
        }
        if (this.data.viewIndex == 2) {
            this.fetchFirstpageContent_grab();
        }
        // 刷新时间
        this.updateDate();
        wx.stopPullDownRefresh();
        setTimeout(function () {
            wx.showToast({
                title: '完成刷新',
                icon: 'none'
            });
        }, 1000);

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        console.log('触底')
        var that = this;
        let num = that.data.mPageNum;
        that.setData({
            mPageNum: num += 1
        });
        // 刷新页面订单数据
        if (this.data.viewIndex == 1) {
            this.fetchFirstpageContent_accept();
        }
        if (this.data.viewIndex == 2) {
            this.fetchFirstpageContent_grab();
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /**
     * 跳转订单详情
     */
    toOrderDetails: function (e) {
        var that = this
        // 获取当前订单的索引
        const orderIndex = e.currentTarget.dataset.index;
        const ChooseOrder = that.data.FirstPageContent[orderIndex]; // 获取选择的订单信息
        console.log("测试：", ChooseOrder)
        //  用户点击之后，调用修改已读状态接口
        wx.request({
            url: api.upAppointUnread,
            method: 'POST',
            data: {
                workOrderCode: ChooseOrder.workOrderCode,
                electricianCode: that.data.electricianCode,
            },
            success: function (res) {
                if (res.data.code == 200) {
                    console.log("修改当前状态为已读")
                }
            }
        })
        wx.navigateTo({
            url: `/pages/FirstPage/order-1/order-1?workOrderCode=${ChooseOrder.workOrderCode}`
        });
    },
})